//
//  STTools_ImageAutoChoseView.m
//  Marriage
//
//  Created by coder on 2018/4/25.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#define TMImageminimumLineSpacing  1
//每行最多多少数量 包括加号
#define TMImageMaxRowNum  4
//父视图 宽度
#define STTools_ImageAutoChoseViewWitdh (STONEOBS_UI_UISCREEN_WIDTH - 20)
#define TMImageWitdh  ( (STTools_ImageAutoChoseViewWitdh - (TMImageMaxRowNum - 1)*TMImageminimumLineSpacing)/TMImageMaxRowNum)
#import "TZImagePickerController.h"
@interface  STTools_ImageAutoChoseViewCollectionCell:UICollectionViewCell
@property(nonatomic, strong) STButton                     *imageButton;/**< button */
@end
@implementation STTools_ImageAutoChoseViewCollectionCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self stoneobs_ui_configSubView];
    }
    return self;
}
#pragma mark --subView
- (void)stoneobs_ui_configSubView{
    self.imageButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)
                                                 title:nil
                                            titleColor:nil
                                             titleFont:0
                                          cornerRadius:0
                                       backgroundColor:nil
                                       backgroundImage:nil
                                                 image:nil];
    self.imageButton.showCloseButton = YES;
    self.imageButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.imageButton];


    
    
}
- (void)layoutSubviews{
    self.imageButton.frame = self.bounds;
    self.imageButton.closeButton.right = self.imageButton.width;
}
@end
#import "STTools_ImageAutoChoseView.h"


@interface STTools_ImageAutoChoseView()
<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
STBWBrowserViewControllerDelegate>


@property(nonatomic, strong) STButton                             *addButton;/**< 添加按钮 */
@property(nonatomic, strong) UICollectionViewFlowLayout                     *layout;/**<  */
@property(nonatomic, assign) CGFloat                     itemWitdh;/**<  */
@end
@implementation STTools_ImageAutoChoseView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.maxCount = 9;
        
        self.itemWitdh =  (self.width - TMImageminimumLineSpacing * (TMImageMaxRowNum - 1) )/ TMImageMaxRowNum;
        self.height =  self.itemWitdh + 2 * TMImageminimumLineSpacing;
        self.backgroundColor = [UIColor clearColor];
        STBWPhotoModel * model = STBWPhotoModel.new;
        model.originImage = [UIImage imageNamed:@"sctp"];
        model.thumbImage = [UIImage imageNamed:@"sctp"];
        [self.dataSouce addObject:model];
        [self stoneobs_ui_configSubView];
    }
    return self;
}
- (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection{
    _scrollDirection = scrollDirection;
    UICollectionViewFlowLayout * flow = [self defultLayout];
    flow.scrollDirection = scrollDirection;
    [self.collectionView setCollectionViewLayout:flow animated:YES];
    [self.collectionView reloadData];
    [self stoneobs_fun_updateCollectonViewFrame];
}
- (NSMutableArray<STBWPhotoModel *> *)dataSouce{
    if (!_dataSouce) {
        _dataSouce = [NSMutableArray new];
    }
    return _dataSouce;
}
- (void)setMaxCount:(NSInteger)maxCount{
    _maxCount = maxCount + 1;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = [self defultLayout];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, TMImageminimumLineSpacing, self.width, self.height - 2 * TMImageminimumLineSpacing) collectionViewLayout:flow];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[STTools_ImageAutoChoseViewCollectionCell class] forCellWithReuseIdentifier:@"item"];
    }
    return _collectionView;
}
- (UICollectionViewFlowLayout*)defultLayout{
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.minimumLineSpacing = TMImageminimumLineSpacing;
    flow.minimumInteritemSpacing = TMImageminimumLineSpacing;
    flow.sectionInset = UIEdgeInsetsZero;
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    return flow;
    
}
- (void)setAddImage:(UIImage *)addImage{
    _addImage = addImage;
    if (!addImage) {
        addImage = [UIImage imageNamed:@"sctp"];
    }
    STBWPhotoModel * model = self.dataSouce.firstObject;
    model.originImage = addImage;
    model.thumbImage = addImage;
    [self.collectionView reloadData];
}
#pragma mark --subView
- (void)stoneobs_ui_configSubView{
    [self insertSubview:self.collectionView atIndex:0];
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake( self.itemWitdh,  self.itemWitdh);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    STTools_ImageAutoChoseViewCollectionCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.backgroundColor = UIColor.clearColor;
    STBWPhotoModel * model = self.dataSouce[indexPath.row];
    UIImage * image = model.originImage?model.originImage:model.thumbImage;
    [item.imageButton setImage:image forState:UIControlStateNormal];
    item.imageButton.closeButton.right = item.width;
    
    
    item.backgroundColor = WH_UICOLOR_FROM_RGBA(0xF9F9F9);
    __weak typeof(self) weakSelf =  self;
    if (indexPath.row == 0) {
        [item.imageButton setShowCloseButton:NO];
        [item.imageButton stoneobs_fun_touch_handle:^(UIButton *sender) {
            [weakSelf stoneobs_action_onSelctedAddButton];
        }];
        [item.imageButton setImage:nil forState:UIControlStateNormal];
        [[item viewWithTag:10001] removeFromSuperview];
        [[item viewWithTag:10000] removeFromSuperview];
        [[item viewWithTag:10002] removeFromSuperview];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.itemWitdh, self.itemWitdh)];
        imageView.image = [UIImage imageNamed:@"sctp"];
        imageView.contentMode = UIViewContentModeScaleToFill;
        [item addSubview:imageView];
        imageView.tag = 10000;
        
        STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, item.width, 20)
                                                         text:@"上传图片"
                                                    textColor:STONEOBS_UI_SECEND_TEXT_COLOR
                                                         font:14
                                                  isSizetoFit:NO
                                                textAlignment:NSTextAlignmentCenter];
//        [item addSubview:titleLable];
        titleLable.centerX = item.width / 2;
        titleLable.top = item.height/2 + 10;
        titleLable.tag = 10001;
        
    }else{
        [[item viewWithTag:10001] removeFromSuperview];
        [[item viewWithTag:10000] removeFromSuperview];
        [[item viewWithTag:10002] removeFromSuperview];
        STButton * button = [[STButton alloc] initWithFrame:CGRectMake(0, -2, 22, 22)
                                                      title:nil
                                                 titleColor:nil
                                                  titleFont:0
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:[UIImage imageNamed:@"shanchu"]
                                                      image:nil];
        [button stoneobs_fun_touch_handle:^(UIButton *sender) {
            
        }];
        if (self.cannotEdit) {
            button.hidden = YES;
        }
        button.right = item.width+2;
        [button stoneobs_fun_touch_handle:^(UIButton *sender) {
            [weakSelf stoneobs_action_onSelectedDelButtonWithIndexPath:indexPath];
        }];
        [item addSubview:button];
        button.tag = 10002;
        [item.imageButton setShowCloseButton:NO];
        [item.imageButton setCloseAction:^(UIButton *sender) {
            [weakSelf stoneobs_action_onSelectedDelButtonWithIndexPath:indexPath];
        }];
        [item.imageButton stoneobs_fun_touch_handle:^(UIButton *sender) {
            [weakSelf stoneobs_action_onSelctedButtonWithIndexPath:indexPath];
        }];
    }
    item.clipsToBounds = NO;
    return item;
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma mark --public Method
- (void)stoneobs_fun_stoneobs_fun_addImageModels:(NSArray<STBWPhotoModel *> *)imageModels{
    [self.dataSouce addObjectsFromArray:imageModels];
}
- (void)stoneobs_fun_addImageModel:(STBWPhotoModel *)imageModel{
    [self.dataSouce addObject:imageModel];
}
- (NSArray<UIImage *> *)stoneobs_fun_get_allImages{
    NSMutableArray * array = [NSMutableArray new];
    for (NSInteger i = 1; i<self.dataSouce.count;i ++ ) {
        STBWPhotoModel * model = self.dataSouce[i];
        if (model.originImage) {
           [array addObject:model.originImage];
        }else{
            [array addObject:model.thumbImage];
        }
    }
    return [array copy];
}
- (NSArray<STBWPhotoModel *> *)stoneobs_fun_getallImageModels{
    return [self.dataSouce subarrayWithRange:NSMakeRange(1, self.dataSouce.count - 1)];
}
- (void)stoneobs_fun_cancleImageModel:(STBWPhotoModel *)imageModel{
    if ([self.dataSouce containsObject:imageModel]) {
        [self.dataSouce removeObject:imageModel];
    }
}
- (void)stoneobs_fun_cancleImageModels:(NSArray<STBWPhotoModel *> *)imageModels{
    for (STBWPhotoModel * model in imageModels) {
        if (![self.dataSouce containsObject:model]) {
            NSLog(@"数组中含有 不存在的模型");
            return;
        }
    }
    [self.dataSouce removeObjectsInArray:imageModels];
}
- (void)stoneobs_fun_removeImageModelFormIndex:(NSInteger)index{
    [self.dataSouce removeObjectAtIndex:index];
}
- (void)stoneobs_fun_updateCollectonViewFrame{
    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
        CGFloat num = ((self.dataSouce.count) / 4.0);
        if (num - @(num).integerValue > 0.01) {
            num = @(num+1).integerValue;
        }
        self.collectionView.height =  self.itemWitdh * num ;
        self.collectionView.scrollEnabled = NO;
        self.height = self.collectionView.bottom;
        if (self.frameDidChangedHandle) {
            self.frameDidChangedHandle(self);
        }
    }else{
        self.collectionView.scrollEnabled = YES;
        self.height = self.itemWitdh;
        self.collectionView.height = self.itemWitdh;
        if (self.frameDidChangedHandle) {
            self.frameDidChangedHandle(self);
        }
    }


}
#pragma mark --Action Method
- (void)stoneobs_action_onSelctedAddButton{
    if (self.cannotEdit) {
        return;
    }
    UIViewController * vc = [UIApplication sharedApplication].delegate.window.rootViewController;
    TZImagePickerController * controller =  [[TZImagePickerController alloc] init];
    controller.maxImagesCount = self.maxCount - self.dataSouce.count  ;
    controller.allowPickingGif = NO;
    controller.allowTakeVideo = YES;
    controller.allowPickingVideo = NO;
    controller.barItemTextColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    [controller setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        for (UIImage * image in photos) {
            STBWPhotoModel * model = STBWPhotoModel.new;
            model.thumbImage = image;
            model.originImage = image;
            [self.dataSouce addObject:model];
        }
        [self stoneobs_fun_updateCollectonViewFrame];
        [self.collectionView reloadData];
    }];
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    }
    [vc presentViewController:controller animated:YES completion:nil];
    
}
- (void)stoneobs_action_onSelectedDelButtonWithIndexPath:(NSIndexPath*)indexPath{
    [self stoneobs_fun_removeImageModelFormIndex:indexPath.row];
   // [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    [self stoneobs_fun_updateCollectonViewFrame];
    [self.collectionView reloadData];
    [self.collectionView stoneobs_fun_st_showAnimationWithType:STAnimationTypekCATransitionFade_stoneobs_enum];
}
- (void)stoneobs_action_onSelctedButtonWithIndexPath:(NSIndexPath*)indexPath{
    //点击了某个图片
    NSMutableArray * models = [NSMutableArray new];
    NSArray * modeArray = self.stoneobs_fun_getallImageModels;
    for (STBWPhotoModel * originModel in modeArray) {
        STBWPhotoModel * model = [STBWPhotoModel  new];
        model.originImage = originModel.originImage?originModel.originImage:originModel.thumbImage;
        [models addObject:model];
    }
    STBWBrowserViewController * vc = [[STBWBrowserViewController alloc] initWithArray:models curentIndex:indexPath.row-1];
    vc.shouldHideBottomView = YES;
    vc.delegate = self;
    UIViewController * rootVC = TMUtils.stoneobs_fun_get_currentTopController;
    [rootVC presentViewController:vc animated:NO completion:nil];
}
#pragma mark --STBWBrowserViewControllerDelegate
- (UIView*)browserControllerDidScrollToIndexpath:(NSIndexPath *)indexPath model:(STBWPhotoModel *)model controller:(STBWBrowserViewController *)controller{
    NSIndexPath * createIndex = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];//多一个加号
    [self.collectionView scrollToItemAtIndexPath:createIndex atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
    NSIndexPath * delIndexpath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
    STTools_ImageAutoChoseViewCollectionCell * item  =(id)[self.collectionView cellForItemAtIndexPath:delIndexpath];
    return   item.imageButton;
}
- (void)rightBarActionFromController:(STBWBrowserViewController *)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
   STTools_ActionSheet * sheet =[STTools_ActionSheet stoneobs_fun_actionSheetWithTitle:nil buttonTitles:@[@"保存"] cancelTitle:@"取消" handle:^(NSInteger index) {
        if (index == 0) {
            STTools_ImageAutoChoseViewCollectionCell * item  =(id)[self.collectionView cellForItemAtIndexPath:curentIndexpath];
            [PHPhotoLibrary stoneobs_fun_saveImageToAssetsLibrary:item.imageButton.currentImage libraryName:UIApplication.stoneobs_fun_st_applictionDisplayName successHandle:^{
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            } errorHandle:^(STSaveImageError_stoneobs_enum error) {
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
            }];
        }
    }];
    [sheet show];
    
                        
//    [controller stoneobs_fun_st_showActionSheet:@[@"保存",@"取消"] andWithBlock:^(int tag) {
//        if (tag == 0) {
//            STTools_ImageAutoChoseViewCollectionCell * item  =(id)[self.collectionView cellForItemAtIndexPath:curentIndexpath];
//            [PHPhotoLibrary stoneobs_fun_saveImageToAssetsLibrary:item.imageButton.currentImage libraryName:UIApplication.stoneobs_fun_st_applictionDisplayName successHandle:^{
//                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//            } errorHandle:^(STSaveImageError_stoneobs_enum error) {
//                [SVProgressHUD showErrorWithStatus:@"保存失败"];
//            }];
//        }
//    }];
}
@end


